package com.whc.gulimall.ware.listener;

import com.rabbitmq.client.Channel;
import com.whc.common.to.OrderTO;
import com.whc.common.to.mq.StockLockedTO;
import com.whc.gulimall.ware.constant.WareMQConstant;
import com.whc.gulimall.ware.service.WareSkuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * @author angaoen
 */
@RabbitListener(queues = WareMQConstant.STOCK_RELEASE_STOCK_QUEUE)
@Slf4j
@Service
public class WareStockListener {

    /**
     * 商品库存
     */
    @Resource
    private WareSkuService wareSkuService;

    /**
     * 监听
     *
     * @param to      to
     * @param message message
     * @param channel channel
     * @throws Exception 异常
     */
    @RabbitHandler
    public void handlerStockLockedRelease(StockLockedTO to, Message message, Channel channel) throws Exception {
        log.info("收到解锁库存的消息");
        try {
            wareSkuService.unlockStock(to);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }
    }

    /**
     * 解锁库存
     *
     * @param to      订单信息
     * @param message message
     * @param channel channel
     */
    @RabbitHandler
    public void handlerStockLockedRelease(OrderTO to, Message message, Channel channel) throws IOException {
        log.info("收到解锁库存的消息");
        try {
            wareSkuService.unlockStock(to);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }
    }

}
